package com.fbinggun.fbinggunutil.fgive;

import com.fbinggun.fbinggunutil.FBinggunUtil;
import com.fbinggun.sql.Formula;
import com.fbinggun.sql.SQLite;
import com.fbinggun.sql.Table;
import org.bukkit.inventory.ItemStack;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FgiveItemSQL   {

    Table itemtable;
    Fgive fgive;
    public FgiveItemSQL(SQLite sql,Fgive fgive) throws SQLException, ClassNotFoundException {
        this.fgive = fgive;
        itemtable = new Table(sql, FBinggunUtil.plugin.getSqlPrefix()+"item");
        if(!itemtable.IsTableNull()){
            itemtable.CreateTable(
                    new Formula("ID", "VARCHAR", 199),
                    new Formula("Info", "text")
            );
        }
    }
    //获取物品数据
    private String getData(String id) throws SQLException, ClassNotFoundException {
        Object o= itemtable.getObject("ID",id,"Info");
        if(o==null|| o.toString().isEmpty()||o.toString().equals("null")){
            return null;
        }
        return o.toString();
    }

    //获取物品
public ItemStack getItem(String id) throws SQLException, ClassNotFoundException {
        String data = getData(id);
        if(data==null){
            return null;
        }
      return   fgive.util.toItemStack(data);
}
//保存数据
public void save(String id,ItemStack item) throws SQLException, ClassNotFoundException {
        String data=fgive.util.toData(item);
        itemtable.setObject("ID",id,"Info",data);
}
//获取全部物品
public Map<String,ItemStack> getItemMap() throws SQLException, ClassNotFoundException {
      Map<String,ItemStack> map=new HashMap<>();
    String t = "select * from "+itemtable.getTablename();
    if(itemtable.getSql().IsConnection()){
        itemtable.getSql().connection();
    }
    Statement statement=    itemtable.getSql().getStatement();
    ResultSet s =statement.executeQuery(t);
    while (s.next()){
        String id =s.getString("ID");
        String info =s.getString("Info");
        map.put(id,fgive.util.toItemStack(info));
    }
    s.close();
    statement.close();
    return map;
}
public List<String> getItemList() throws SQLException, ClassNotFoundException {
        List<String> list=new ArrayList<>();
        Map<String,ItemStack> map = getItemMap();
        list.addAll(map.keySet());
        return list;
}


}
